#!/usr/bin/env python

############################################################################
#  QLyrics - A simple lyrics viewer.                                       #
#  Copyright (C) 2008  hsys <hanshuiys@gmail.com>                          #
#                                                                          #
#  This program is free software; you can redistribute it and/or modify    #
#  it under the terms of the GNU General Public License as published by    #
#  the Free Software Foundation; either version 3 of the License, or       #
#  (at your option) any later version.                                     #
#                                                                          #
#  This program is distributed in the hope that it will be useful,         #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of          #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
#  GNU General Public License for more details.                            #
#                                                                          #
#  You should have received a copy of the GNU General Public License       #
#  along with this program; if not, write to the Free Software Foundation, #
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA       #
############################################################################

import os, sys, signal, time, libqlyrics, mpd;

MPD_HOST = os.environ.get('MPD_HOST', 'localhost')
MPD_PORT = int(os.environ.get('MPD_PORT', 6600))
MPD_LIB_DIR = os.popen("""awk '/^music_directory/ { gsub("\\"", "", $2); print $2 }' /etc/mpd.conf""").read().strip() + "/"

mpdc = None

def getTrackTitle():
    global mpdc
    return mpdc.currentsong()["title"]

def getTrackAlbum():
    global mpdc
    return mpdc.currentsong()["album"]

def getTrackArtist():
    global mpdc
    return mpdc.currentsong()["artist"]

def getTrackLength():
    global mpdc
    return repr(int(mpdc.status()["time"].split(":")[1]) * 1000)

def getTrackFilename():
    global mpdc
    return MPD_LIB_DIR + mpdc.currentsong()["file"]

def getTrackTime():
    global mpdc
    return repr(int(mpdc.status()["time"].split(":")[0]) * 1000)

def getPlayerStatus():
    global mpdc
    StatusTable = {
            "stop" : "Idle",
            "play" : "Playing",
            "pause" : "Paused"
            }
    status = mpdc.status()["state"]
    if (not (status in StatusTable)):
        return status
    status = StatusTable[status]
    return status

def cleanup(signum, frame):
    libqlyrics.stop()

signal.signal(signal.SIGTERM, cleanup)

libqlyrics.setEventHandler("Title", getTrackTitle)
libqlyrics.setEventHandler("Album", getTrackAlbum)
libqlyrics.setEventHandler("Artist", getTrackArtist)
libqlyrics.setEventHandler("Length", getTrackLength)
libqlyrics.setEventHandler("Filename", getTrackFilename)
libqlyrics.setEventHandler("Time", getTrackTime)

if (MPD_LIB_DIR == ""):
    print >>sys.stderr, "--- Failed to get music_directory!"
    sys.exit()
try:
    mpdc = mpd.MPDClient()
    mpdc.connect(MPD_HOST, MPD_PORT);
except:
    print >>sys.stderr, "--- Failed connecting to mpd!"
    sys.exit()

libqlyrics.start()

prevTrack = None
prevStatus = None

while True:
    if (not libqlyrics.isRunning()):
        sys.exit()

    try:
        if (getTrackFilename() != prevTrack):
            prevTrack = getTrackFilename()
            libqlyrics.trackChanged()

        if (getPlayerStatus() != prevStatus):
            prevStatus = getPlayerStatus()
            libqlyrics.statusChanged(prevStatus)
    except:
        break

    time.sleep(1)

libqlyrics.stop()

